<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
     .ani-enter{
       transform: translateX(-100%);
       opacity: 0;
     }
     .ani-enter-active,.ani-leave-active{
       transition: all 300ms;
     }
     .ani-leave-to{
      transform: translateX(100%);
       opacity: 0;
     }
     html{
       overflow-x: hidden;
     }

  </style>
</head>

<body>
  <div id="app">
    <!-- 跳转路由组件 -->
    <button @click="enterHome">到首页</button>
    <button @click="enterNews">到新闻页</button>
    <button @click="enterAbout">到关于我们页</button>
    
    <!-- 在 视图上 指定路由组件出口 -->
    <transition name="ani" mode="out-in">
      <router-view></router-view>
    </transition>
    
  </div>
  <script src="./vue.js"></script>
  <script src="./vue-router.js"></script>
  <script>
    // 准备路由组件对象 为了注册路由组件
    const Home = {
      template: `
        <div>
          <h2>我是首页</h2>  
        </div>
      `
    }
    const News = {
      template: `
        <div>
          <h2>我是新闻页</h2>  
        </div>
      `,
      mounted(){
        console.log(this.$router);
        console.log(this.$router.getRoutes());
      }
    }
    const About = {
      template: `
        <div>
          <h2>关于我们</h2>  
        </div>
      `
    }
    const NotFound = {
      template: `
        <div>
          <h2>404啦</h2>  
        </div>
      `
    }
    const Login = {
      template: `
        <div>
          <h2>登录页</h2>  
        </div>
      `
    }
    // 创建一个 router 对象
    const routes = [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home
      },
      {
        path: '/news',
        component: News
      },
      {
        path:'/about',
        component: About
      },
      {
        path: '*',
        component: NotFound
      }
    ]
    const router = new VueRouter({
      // routes 路由规则
      routes,
      scrollBehavior (to, from, savedPosition) {
        /*
        每一次切换路由时触发 
        需要return 一个对象
        {
          x: 0,
          y: 0
        }
        x水平滚动条位置
        y代表垂直滚动条
        */
       if(savedPosition){
        return savedPosition;
       }else{
         return {
           x:0,
           y:0
         }
       }
       
      }
    });
    // 将router对象 挂载到实例上
    const vm = new Vue({
      el: "#app",
      router,
      methods: {
        enterHome(){
          this.$router.push("/home")
        },
        enterNews(){
          this.$router.push("/news")
        },
        enterAbout(){
          this.$router.replace("/about")
        },
        addRoutes(){
          this.$router.addRoutes([
            {
              path: '/login',
              component: Login
            }
          ])
        }
      }
    })
  </script>
</body>

</html>